import React, { useState, useEffect } from "react";
import {
  Form,
  Input,
  InputNumber,
  Popconfirm,
  Table,
  Typography,
  Button,
  Select
} from "antd";
import { useLocation, useNavigate } from "react-router-dom";
import "./tableedit.scss";
const { Search } = Input;

// EditableCell 修改：支持 select 类型输入
const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  options, // 传递的下拉选项
  children,
  ...restProps
}) => {
  let inputNode;

  if (inputType === "number") {
    inputNode = <InputNumber />;
  } else if (inputType === "select") {
    inputNode = (
      <Select
        options={options}
        style={{ width: "100%" }}
      />
    );
  } else {
    inputNode = <Input />;
  }

  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={`${record.key}-${dataIndex}`}  // 确保 name 唯一
          style={{ margin: 0 }}
          initialValue={record[dataIndex]}  // 默认值设为原数据
          rules={[
            {
              required: false,
              message: `请输入 ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};


const TableEdit_zujian = () => {
  const [pageSize, setPageSize] = useState(10);
  const [searchText, setSearchText] = useState('');
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const location = useLocation();
  const [originData, setOriginData] = useState([
      {
        key: '1', page: '2003', type: '页项', componentName: 'P2003_PROJECT', componentLabel: '项目',
      },
      {
        key: '2', page: '2006', type: '页项', componentName: 'P2006_PROJECT', componentLabel: '用户名',
      },
      {
        key: '3', page: '9999', type: '区域', componentName: 'R9999_LOGIN', componentLabel: '登录区域',
      },
      {
        key: '4', page: '2003', type: '页项', componentName: 'P2003_PROJECT', componentLabel: '项目',
      },
      {
        key: '5', page: '2006', type: '页项', componentName: 'P2006_PROJECT', componentLabel: '用户名',
      },
      {
        key: '6', page: '9999', type: '区域', componentName: 'R9999_LOGIN', componentLabel: '登录区域',
      },
      {
        key: '7', page: '2003', type: '页项', componentName: 'P2003_PROJECT', componentLabel: '项目',
      },
      {
        key: '8', page: '2006', type: '页项', componentName: 'P2006_PROJECT', componentLabel: '用户名',
      },
      {
        key: '9', page: '9999', type: '区域', componentName: 'R9999_LOGIN', componentLabel: '登录区域',
      },
      {
        key: '10', page: '2003', type: '页项', componentName: 'P2003_PROJECT', componentLabel: '项目',
      },
      {
        key: '11', page: '2006', type: '页项', componentName: 'P2006_PROJECT', componentLabel: '用户名',
      },
      {
        key: '12', page: '9999', type: '区域', componentName: 'R9999_LOGIN', componentLabel: '登录区域',
      },
    ]);
  const [selectedDelRowKeys, setselectedDelRowKeys] = useState(() => {
    return location.state?.selectedDelRowKeys || [];
  });
  useEffect(() => {
    if (!selectedDelRowKeys.length) return; // 避免 selectedDelRowKeys 为空时触发
    setOriginData((prevData) =>
      prevData.filter((item) => !selectedDelRowKeys.includes(item.key))
    );
  }, [selectedDelRowKeys]); // 只监听 `selectedDelRowKeys`
  console.log(originData)
  const navigate = useNavigate();
  const [data, setData] = useState(originData);
  useEffect(() => {
    setData(originData); // 当 originData 变化时，更新 data
  }, [originData]);
  // 初始化编辑状态为从 SelectPage 传递过来的选中行 key（如果有）
  const [editingKeys, setEditingKeys] = useState(() => {
    return location.state?.selectedKeys || [];
  });
  const onSearch = (value) => {
    setSearchText(value);
  };
  const filteredData = data.filter(item =>
    Object.values(item).some(value =>
      value && String(value).toLowerCase().includes(searchText.toLowerCase()) // 先检查 value 是否存在
    )
  );
  const goToParent = () => {
    navigate("..");
  };

  // 初始化表单数据，填充选中行
  useEffect(() => {
    if (location.state?.selectedRows) {
      const initialValues = location.state.selectedRows.reduce((acc, row) => {
        ["page", "pagename", "pagetitle", "template", "permission"].forEach(
          (field) => {
            acc[`${row.key}-${field}`] = row[field];
          }
        );
        return acc;
      }, {});
      form.setFieldsValue(initialValues);
    }
  }, [location.state, form]);

  const isEditing = (record) => editingKeys.includes(record.key);

  // 保存所有编辑行
  const saveAll = async () => {
    try {
      const values = await form.validateFields();
      console.log("表单数据:", values); // 调试输出
  
      const newData = data.map((item) => {
        if (editingKeys.includes(item.key)) {
          return {
            ...item,
            page: values[`${item.key}-page`] ?? item.page,  // 只更新非空值
            pagename: values[`${item.key}-pagename`] ?? item.pagename,
            pagetitle: values[`${item.key}-pagetitle`] ?? item.pagetitle,
            template: values[`${item.key}-template`] ?? item.template,
            permission: values[`${item.key}-permission`] ?? item.permission,
          };
        }
        return item;
      });
  
      console.log("更新后的数据:", newData);
  
      setData(newData);
      setOriginData(newData);  // 确保 originData 也同步更新
      setEditingKeys([]);
    } catch (err) {
      console.log("验证失败:", err);
    }
  };
  
  

  const columns = [
    {
      title: '页', dataIndex: 'page', key: 'page', align: 'left', width: 100, render: (text) => (
        <span
          style={{ color: '#1890ff', cursor: 'pointer' }}
          onClick={() => navigate(`/page/${text}`)}
        >
          {text}
        </span>
      )
    },
    { title: '类型', dataIndex: 'type', key: 'type', align: 'left', width: 130 },
    { title: '组件名称', dataIndex: 'componentName', key: 'componentName', align: 'left', width: 150,render: (text) => (
      <span
        style={{ color: '#1890ff', cursor: 'pointer' }}
        onClick={() => navigate(`/page/${text}`)}
      >
        {text}
      </span>
    ) },
    { title: '组件标签', dataIndex: 'componentLabel', key: 'componentLabel', align: 'left', width: 120 ,editable: true},
  ];

  const mergedColumns = columns.map((col) => {
    if (!col.editable) return col;
    return {
      ...col,
      onCell: (record) => ({
        record,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
        inputType: col.inputType || "text", // 传递 inputType
        options: col.options || [], // 传递 options
      }),
    };
  });

  return (
    <Form form={form} component={false}>
      <div style={{padding:16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <Button
              type="primary"
              onClick={saveAll}
              loading={loading}
              style={{marginLeft:'5px',borderRadius: '3px', padding: '16px' }}
            >
              保存编辑
            </Button>
            <Popconfirm
              title="确定要取消编辑吗？"
              onConfirm={goToParent} // 这里要直接传入函数
              okText="是"
              cancelText="否"
          >
            <Button
              type="primary"
              loading={loading}
              style={{marginLeft:'15px',borderRadius: '3px', padding: '16px' }}
            >
              取消编辑
            </Button>
            </Popconfirm>
          </div>
        <Search placeholder="搜索" onSearch={onSearch} style={{ width: 200, marginRight:'20px' }} />
      </div>
      <Table
        dataSource={filteredData}
        style={{ marginLeft: '5px', marginRight: '20px', marginTop: '16px' }}
        columns={mergedColumns}
        rowKey="key"
        pagination={{
          pageSize,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50'],
          onShowSizeChange: (current, size) => setPageSize(size),
        }}
        components={{
          body: {
            cell: EditableCell,
          },
        }}
        bordered
      />
    </div>
    </Form>
  );
};

export default TableEdit_zujian;
